package com.zxh.blog.fragment

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.zxh.blog.R
import com.zxh.blog.adapter.LinkRecyclerAdapter
import com.zxh.blog.bean.Link
import com.zxh.blog.bean.ResponseJson
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

class LinkFragment : Fragment() {

    private lateinit var mRecyclerView: RecyclerView

    private lateinit var mAdapter: LinkRecyclerAdapter

    private var mLinkList = ArrayList<Link>()

    private val mBaseURL = "http://43.140.201.43:7777/link/getAllLink"

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_link, container, false)
        // 调用后端接口接收并解析json数据
        initDataByOkhttp(mBaseURL)
        // 初始化RecyclerView
        mRecyclerView = view.findViewById(R.id.linkList)
        // 初始化适配器
        mAdapter = LinkRecyclerAdapter(requireContext())
        return view
    }

    override fun onStart() {
        super.onStart()
        mAdapter.setClickListener(object : LinkRecyclerAdapter.ClickListener{
            override fun onClick(position: Int, articleList: ArrayList<Link>) {
                val intent = Intent(Intent.ACTION_VIEW)
                intent.data = Uri.parse(articleList[position].address)
                context?.startActivity(intent)
            }
        })
    }

    private fun initDataByOkhttp(url: String) {
        val client = OkHttpClient()
        val request = Request.Builder()
            .url(url)
            .build()
        client.newCall(request).enqueue(object : Callback {
            override fun onResponse(call: Call, response: Response) {
                val responseData = response.body?.string()
                if (responseData != null) {
                    parseJSONWithGSON(responseData)
                    // 将UI更新操作移动到主线程
                    Handler(Looper.getMainLooper()).post {
                        // 更新UI视图
                        updateUI()
                    }
                }
            }

            override fun onFailure(call: Call, e: IOException) {}
        })
    }

    private fun updateUI() {
        // 在这里更新UI视图
        // 设置布局和适配器
        val layoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL)
        mRecyclerView.layoutManager = layoutManager
        mRecyclerView.adapter = mAdapter
        mAdapter.setData(mLinkList)
    }

    private fun parseJSONWithGSON(responseData: String) {
        val gson = Gson()
        val typeToken = object : TypeToken<ResponseJson<List<Link>>>() {}.type
        val data: ResponseJson<List<Link>> = gson.fromJson(responseData, typeToken)
        mLinkList = data.data as ArrayList<Link>
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.d(TAG, "onViewCreated: ")
    }

    companion object {
        private const val TAG = "LinkFragment"
    }
}